import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:jump_scape/js_data/js_box/js_init.dart';
import 'package:jump_scape/js_data/js_member.dart';

import '../js_config.dart';
import '../objectbox.g.dart';
import 'js_box/js_coin_shop.dart';
import 'js_http/js_http.dart';

class JsCoinShop {
  Future<List<CoinShopBox>> getCoinList() async {
    List<CoinShopBox> list = [];

    try {
      final body = await JsHttp.post(JsApp.jsHttpCoinList, true, {"isIncludeSubscription": "false", "payChannel": "IAP"});
      bool isSucc = body[1];

      if (isSucc) {
        final List<dynamic> payInfos = body[2];

        var id = 0;
        for (Map<String, dynamic> payInfo in payInfos) {
          id++;
          list.add(CoinShopBox(
            id: id,
            discount: payInfo["discount"].toString(), // 折扣
            exchangeCoin: payInfo["exchangeCoin"].toString(), // 兑换金币的数量
            goodsId: payInfo["goodsId"].toString(), // 商品 id
            originalPrice: payInfo["originalPrice"].toString(), // 原价
            price: payInfo["price"].toString(), // 现价
            code: payInfo["code"].toString(), // 商品编号
            tags: payInfo["tags"].toString(), // 当tags有值且为'HOT'展示热度标志🔥, 非HOT值则展示促销标签，内容从tags里面取, tags值为空或不返回则不展示热度标志和促销标签
          ));
        }

        JsObjectBox.coinShopBox.removeAll();
        JsObjectBox.coinShopBox.putMany(list);
      }
    } catch (e) {
      e.printError();
    }

    if (list.isEmpty) {
      list.addAll(JsObjectBox.coinShopBox.getAll());
    }

    return list;
  }

  Future<bool> consumption({
    required String coin,
    required Function(bool isSucc, bool isInsufficient, String msg) call,
  }) async {
    await JsMember().synchronizationMember(onSuccess: (member) {}, onFailed: (msg) {});

    final setting = await JsObjectBox.setting;
    var member = JsObjectBox.memberBox.query(MemberBox_.userId.equals(setting.userId)).build().findFirst();
    final balance = member?.balance ?? '0';

    double coinD = double.tryParse(coin) ?? 0.0;
    double balanceD = double.tryParse(balance) ?? 0.0;

    if (coinD > balanceD) {
      call(false, true, '');
      return false;
    }

    final body = await JsHttp.post(JsApp.jsHttpReviewModeConsume, true, {"outlay": coin, "source": "iap"});
    String code = body[0];
    bool isSucc = body[1];

    await JsMember().synchronizationMember(onSuccess: (member) {}, onFailed: (msg) {});

    if (JsApp.jsCodeCoinIsInsufficient == code) {
      call(isSucc, true, body[2]);
    } else {
      call(isSucc, false, body[2].toString());
    }

    return isSucc;
  }

  Future<void> recharge({
    required String goodsCode,
    required Function(String orderNo) onSuccess,
    required Function(String msg) onFailed,
  }) async {
    final body = await JsHttp.post(JsApp.jsHttpRecharge, true, {"goodsCode": goodsCode, "payChannel": "IAP", "entry": "", "source": ""});
    bool isSucc = body[1];

    if (isSucc) {
      final Map<String, dynamic> payInfos = body[2];

      debugPrint("[recharge] ✅ $payInfos");

      String orderNo = payInfos["orderNo"];
      onSuccess(orderNo);
    } else {
      onFailed(body[2]);
    }
  }

  Future<void> checkRecharge({
    required String orderNo,
    required String payload,
    required String transactionId,
    required Function() onSuccess,
    required Function(String msg) onFailed,
  }) async {
    final body = await JsHttp.post(JsApp.jsHttpCheckRecharge, true, {"orderNo": orderNo, "payload": payload, "transactionId": transactionId, "type": "1"});
    bool isSucc = body[1];

    if (isSucc) {
      onSuccess();
    } else {
      onFailed(body[2]);
    }
  }
}
